﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace Cheetah_Fast_Banking_App
{
    public static class ExtensionMethods
    {
        public static void Refresh<T>(this ObservableCollection<T> me)
        {
            // force update
            // only refreshes those that are added, removed, or changed, not all of them, so...
            List<T> list = new List<T>();
            foreach (T t in me)
                list.Add(t);
            me.Clear();
            foreach (T t in list)
                me.Add(t);
        }        

        public static void Sort<T>(this ObservableCollection<T> me, IComparer<T> comparer)
        {
            me.QuickSort(comparer);
        }

        //http://blogs.msdn.com/b/zhanli/archive/2010/07/28/algorithms-in-c-quick-sort-part-one.aspx
        private static void QuickSort<T>(this Collection<T> me, IComparer<T> comparer = null)
        {
            if (me.Count <= 1)
                return;

            if (comparer == null)
                comparer = Comparer<T>.Default;

            QuickSort(me, 0, me.Count - 1, comparer);
        }

        private static void QuickSort<T>(this Collection<T> me, int leftIndex, int rightIndex, IComparer<T> comparer)
        {
            //base case
            if (rightIndex <= leftIndex)
                return;
            
            int pivotIndex = leftIndex;
            T pivot = me[leftIndex];

            // partition
            for (int i = leftIndex + 1; i <= rightIndex; i++)
            {
                if (comparer.Compare(pivot, me[i]) > 0)
                {
                    me.Swap(++pivotIndex, i);
                }
            }

            me.Swap(leftIndex, pivotIndex);

            //recurively QuickSort partitions
            QuickSort(me, leftIndex, pivotIndex - 1, comparer);
            QuickSort(me, pivotIndex + 1, rightIndex, comparer);
        }

        private static void Swap<T>(this Collection<T> me, int p1, int p2)
        {
            T temp = me[p1];
            me[p1] = me[p2];
            me[p2] = temp;
        }

        private static void Swap<T>(this ObservableCollection<T> me, int p1, int p2)
        {
            if (p1 == p2)
                return;

            me.Move(p1, p2);

            if (p1 < p2)
                me.Move(p2 - 1, p1);  
            else if (p2 < p1)
                me.Move(p2 + 1, p1); 
        }
    }
}
